/**
 * 分组报表页面逻辑
 *
 * @版权所有 rem.studio
 */
import React, { PureComponent } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Button, Table } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './GroupChart.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ groupChart, loading }) => ({
  groupChart,
  loading: loading.models.groupChart
}))
@Form.create()
class GroupChart extends PureComponent {
  state = {
    formValues: {},
  };

  columns = [
    {
      title: formatMessage({ id: 'app.analysis.shopname' }),
      dataIndex: 'name'
    },
    {
      title: formatMessage({ id: 'app.analysis.salestype' }),
      dataIndex: 'salesType'
    },
    {
      title: formatMessage({ id: 'app.analysis.visitstraffic' }),
      children: [{
        title: formatMessage({ id: 'app.analysis.visits' }),
        dataIndex: 'visits',
        render: (value, row, index) => {
          const obj = {
            children: value,
            props: {},
          };
          if (index === 2) {
            obj.props.rowSpan = 4;
          }
          if (index === 3 || index === 4 || index === 5) {
            obj.props.rowSpan = 0;
          }
          return obj;
        }
      },
      {
        title: formatMessage({ id: 'app.analysis.traffic' }),
        dataIndex: 'flow',
        render: (text, row, index) => {
          return {
            children: <a>{text}</a>
          };
        },
      }]
    },
    {
      title: formatMessage({ id: 'app.analysis.userpayment' }),
      children: [{
        title: formatMessage({ id: 'app.analysis.payments' }),
        dataIndex: 'paymentQuantity'
      },
      {
        title: formatMessage({ id: 'app.analysis.table.users' }),
        dataIndex: 'userCount'
      }]
    },
    {
      title: formatMessage({ id: 'app.analysis.table.weekly-range' }),
      dataIndex: 'gain',
      render: val => <span>{val + '%'}</span>
    },
    {
      title: formatMessage({ id: 'app.analysis.conversion-rate' }),
      dataIndex: 'cvr',
      render: val => <span>{val * 100 + '%'}</span>
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'groupChart/fetch'
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'groupChart/fetch',
      payload: params
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {}
    });
    dispatch({
      type: 'groupChart/fetch'
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      this.setState({
        formValues: values
      });
      dispatch({
        type: 'groupChart/fetch',
        payload: values
      });
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.analysis.salestype' })}>
              {getFieldDecorator('salesType')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} type="primary" icon="reload">
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { groupChart: { data }, loading } = this.props;
    let countUser = 0;
    for (let key in data.list) {
      countUser += data.list[key].userCount;
    }
    return (
     <div content={formatMessage({ id: 'app.analysis.groupchart' })}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <Table
              bordered={true}
              rowKey={record => record.id}
              loading={loading}
              dataSource={data ? data.list : []}
              pagination={false}
              columns={this.columns}
              onChange={this.handleBasicTableChange}
              title={() => formatMessage({ id: 'app.analysis.groupchartstatistics' })}
              footer={() => formatMessage({ id: 'app.analysis.totaluser' }) + '\t' + countUser}
            />
          </div>
        </Card>
     </div>
    );
  }
}

export default GroupChart;
